package com.example.myapplication

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import java.text.DecimalFormat

class MySeekBar(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private val arcPaint = Paint()

    private val percentPaint = Paint()

    /**
     * 需要get/set，因为ObjectAnimator需要依据progress计算动画进度和实际属性。
     *
     * val animator = ObjectAnimator.ofFloat(seekBar, "progress", 0F, 100F)
     */
    @androidx.annotation.FloatRange(from = 0.0, to = 100.0)
    private var progress = 0f

    private fun getProgress() = progress


    private fun setProgress(p: Float) {
        progress = p
        postInvalidate()
    }

    init {
        arcPaint.isAntiAlias = true
        arcPaint.style = Paint.Style.STROKE
        arcPaint.strokeWidth = 30F
        arcPaint.strokeCap = Paint.Cap.ROUND
        arcPaint.color = Color.RED

        percentPaint.isAntiAlias = true
        percentPaint.textSize = 100F
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val middle = (measuredWidth / 2).toFloat()
        if (progress == 0F) {
            canvas?.drawPoint(middle, 700F, arcPaint)
        } else {
            val angle = progress / 100 * 360
            canvas?.drawArc(middle - 300, 100F, middle + 300, 700F, 90F, angle, false, arcPaint)
        }
        val percent = getPercentStr((progress / 100).toDouble())
        canvas?.drawText(percent, middle - 100, 440F, percentPaint)
    }

    private fun getPercentStr(arg: Double): String {
        val format = DecimalFormat("#%")
        return format.format(arg)
    }
}